<!--  线 + 柱混合图 -->
<template>
  <el-card>
    <template #header>
      <div class="flex-x-between">
        <div class="flex-y-center">各保险公司统计</div>
      </div>
    </template>

    <div :id="id" :class="className" :style="{ height, width }" />
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';

import { listNyt7StatisticsInsureNumCompany } from '@/api/Nyt7StatisticsInsureNumCompany/Nyt7StatisticsInsureNumCompany';
import { ref, watch, onMounted, onBeforeUnmount, onActivated, markRaw } from 'vue';

const company = ref([]);
const processedData = ref([]);
const chart: Ref<echarts.ECharts | null> = ref(null);

const props = defineProps({
  id: {
    type: String,
    default: 'charts'
  },
  className: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '200px',
    required: true
  },
  height: {
    type: String,
    default: '200px',
    required: true
  }
});

const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};

const loadPolicyCount = async () => {
  try {
    const count = await listNyt7StatisticsInsureNumCompany();
    company.value = count.rows;
    console.log(company.value);
    processedData.value = company.value.map((item) => {
      return [item.company, item.areaAcres, item.areaRatio];
    });
    console.log('111',processedData.value);
  } catch (error) {
    console.error('Failed to fetch policy count:', error);
  }
};

onMounted(async () => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));
  await loadPolicyCount();
  updateChart();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

onActivated(() => {
  handleResize();
});

// 监听 processedData.value 的变化
watch(processedData, () => {
  updateChart();
});

// 更新图表
const updateChart = () => {
  if (chart.value) {
    const option = {
      legend: {},
      tooltip: {},
      dataset: {
        source: [
          ['product', '面积亩数', '面积占比'],
          ...processedData.value.map(item => [item[0], item[1], item[2]])
        ]
      },
      xAxis: { type: 'category' },
      yAxis: {},
      series: [{ type: 'bar' }, { type: 'bar' }]
    };
    chart.value.setOption(option);
  }
};
</script>

<style lang="scss" scoped></style>
